var express = require('express');
var router = express.Router();
var { aesDecrypt, keys } = require("../untils/ase");
var { conn, isError, isLogin } = require("../untils");
var { ObjectID } = require("mongodb");
var { series } = require("async");

/* GET home page. */
router.get('/', function (req, res) {
  var session_username = req.session.username;
  conn((err, db) => {
    isError(err, res, db);
    var news_index_info = db.collection("news_index_info");
    news_index_info.find({}, {}).sort({ ptime: -1 }).limit(10).toArray((err, result) => {
      isError(err, res, db);
      res.render("index", { session_username, result })
      db.close();
    });
  });
});

router.get('/index', function (req, res) {
  var skip_key = req.query.skip_key * 1;
  var db_name = req.query.db_name;
  var news_info = null;
  conn((err, db) => {
    isError(err, res, db);
    if (db_name === "index") {
      news_info = db.collection("news_index_info");
    } else if (db_name === "television") {
      news_info = db.collection("news_television_info");
    } else if (db_name === "movie") {
      news_info = db.collection("news_movie_info");
    } else if (db_name === "star") {
      news_info = db.collection("news_star_info");
    } else if (db_name === "music") {
      news_info = db.collection("news_music_info");
    }
    news_info.find({}, {}).sort({ ptime: -1 }).skip(skip_key).limit(10).toArray((err, result) => {
      isError(err, res, db);
      res.json(result);
      db.close();
    });
  });
});

router.get('/television', function (req, res) {
  var session_username = req.session.username;
  conn((err, db) => {
    isError(err, res, db);
    var news_television_info = db.collection("news_television_info");
    news_television_info.find({}, {}).sort({ ptime: -1 }).limit(10).toArray((err, result) => {
      isError(err, res, db);
      res.render("television", { session_username, result })
      db.close();
    });
  });
});

router.get('/movie', function (req, res) {
  var session_username = req.session.username;
  conn((err, db) => {
    isError(err, res, db);
    var news_movie_info = db.collection("news_movie_info");
    news_movie_info.find({}, {}).sort({ ptime: -1 }).limit(10).toArray((err, result) => {
      isError(err, res, db);
      res.render("movie", { session_username, result })
      db.close();
    });
  });
});

router.get('/star', function (req, res) {
  var session_username = req.session.username;
  conn((err, db) => {
    isError(err, res, db);
    var news_star_info = db.collection("news_star_info");
    news_star_info.find({}, {}).sort({ ptime: -1 }).limit(10).toArray((err, result) => {
      isError(err, res, db);
      res.render("star", { session_username, result })
      db.close();
    });
  });
});

router.get('/music', function (req, res) {
  var session_username = req.session.username;
  conn((err, db) => {
    isError(err, res, db);
    var news_music_info = db.collection("news_music_info");
    news_music_info.find({}, {}).sort({ ptime: -1 }).limit(10).toArray((err, result) => {
      isError(err, res, db);
      res.render("music", { session_username, result })
      db.close();
    });
  });
});

router.get('/login', function (req, res) {
  var session_username = req.session.username;
  let username = req.query.username;
  if (username) {
    username = aesDecrypt(username, keys);
  }
  res.render('login', { session_username, username, msg: "" });
});

router.get('/register', function (req, res) {
  var session_username = req.session.username;
  res.render('register', { session_username, result: { code: 0, msg: "" } });
});

router.get('/logout', function (req, res) {
  req.session.destroy(() => {
    res.redirect("/");
  });
});

router.get('/details', function (req, res) {
  var session_username = req.session.username;
  var news_user_type = req.session.news_user_type;
  var count = 0;   // 所有评论的条数 
  var totalPage = 0;  //  总页数 
  var pageSize = 5;  // 每页显示 5条
  var pageNo = parseInt(req.query['pageNo']) || 0;  // 当前的页码 
  var _id = ObjectID(req.query._id);
  var db_name = req.query.db_name;
  var news_info = null;
  conn((err, db) => {
    isError(err, res, db);
    if (db_name === "index") {
      news_info = db.collection("news_index_info");
    } else if (db_name === "television") {
      news_info = db.collection("news_television_info");
    } else if (db_name === "movie") {
      news_info = db.collection("news_movie_info");
    } else if (db_name === "star") {
      news_info = db.collection("news_star_info");
    } else if (db_name === "music") {
      news_info = db.collection("news_music_info");
    }
    var news_comments = db.collection("news_comments");
    var news_edit_info = db.collection("news_edit_info");
    series([
      (callback) => {
        news_info.find({ _id }, {}).toArray((err, result) => {
          if (err) {
            callback(err, null);
          } else {
            callback(null, result[0]);
          }
        });
      },
      (callback) => {
        news_comments.find({ status: 1, news_id: _id }, {}).toArray((err, result) => {
          if (err) {
            callback(err, null)
          } else {
            count = result.length;
            totalPage = Math.ceil(count / pageSize);
            pageNo = pageNo >= totalPage ? totalPage : pageNo;
            pageNo = pageNo <= 1 ? 1 : pageNo;
            callback(null, true);
          }
        })
      },
      (callback) => {
        news_comments.find({ status: 1, news_id: _id }, {}).sort({ insert_time: -1 }).skip((pageNo - 1) * pageSize).limit(pageSize).toArray((err, result) => {
          if (err) {
            callback(err, null);
          } else {
            callback(null, result);
          }
        })
      },
      (callback) => {
        news_edit_info.find({ status: 1, news_id: _id }, {}).toArray((err, result) => {
          if (err) {
            callback(err, null);
          } else {
            callback(null, result);
          }
        })
      }
    ], (err, result) => {
      isError(err, res, db);
      res.render('news_details', { session_username, news_result: result[0], comments_result: result[2], db_name, _id, count, totalPage, pageNo, news_user_type, edit_result: result[3] });
      db.close();
    });
  });
});

router.get('/remove_edit', function (req, res) {
  var session_username = req.session.username;
  var remove_id = req.cookies.remove_id;
  var _id = ObjectID(req.query._id);
  var db_name = req.query.db_name;
  var obj = {};
  obj.status = 1;
  if (remove_id !== "-1") {
    obj._id = ObjectID(remove_id);
  }
  isLogin(session_username, res, () => {
    conn((err, db) => {
      isError(err, res, db);
      var news_comments = db.collection("news_comments");
      news_comments.updateMany(obj, { $set: { status: 0 } }, (err, result) => {
        isError(err, res, db);
        res.cookie("remove_id", "", { maxAge: 1 });
        res.redirect(`details?db_name=${db_name}&_id=${_id}`);
        db.close();
      })
    });
  });
});

module.exports = router;
